package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sbt.api.TrackApi;
import com.kgc.sbt.beans.*;
import com.kgc.sbt.service.SearchService;
import com.kgc.sbt.service.UserService;
import com.kgc.sbt.utils.PageSupportUtil;
import com.kgc.sbt.utils.RedisUtils;
import com.kgc.sbt.utils.RequestResult;
import com.kgc.sbt.utils.ResultBuildUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2021/8/16.
 * <p>
 * Author : Lcywings
 * <p>
 * Description :
 */
@RestController
@Slf4j
@Api(tags = " 2 商城大厅操作入口")
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Autowired
    private UserService userService;

    @Reference(timeout = 30000)
    private TrackApi trackApi;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @author : Lcywings
     * @date : 2021/8/16 14:07
     * @acl : true
     * @description : 搜索大厅
     */
    @ApiOperation(value = "搜索大厅", notes = "支持分页，支持模糊搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keywords", required = false, defaultValue = "", value = "搜索关键词"),
            @ApiImplicitParam(name = "pageSize", required = true, defaultValue = "5", value = "页面容量"),
            @ApiImplicitParam(name = "pageNo", required = true, defaultValue = "1", value = "当前页")
    })
    @ApiResponses({
            @ApiResponse(code = 0000, message = "SUCCESS")
    })
    @GetMapping("/productList")
    public RequestResult<PageSupportUtil<Product>> productList(String keywords,
                                                               @RequestParam Integer pageSize,
                                                               @RequestParam Integer pageNo) {
        log.info("调用service接口进行搜索大厅查询，参数：{}，{}，{}", keywords, pageSize, pageNo);
        if (StringUtils.isEmpty(keywords)) {
            keywords = "";
        }

        return ResultBuildUtil.success(searchService.queryProductList(keywords, pageSize, pageNo));
    }


    /**
     * @author : Lcywings
     * @date : 2021/8/17 12:27
     * @acl : true
     * @description :
     */
    @ApiOperation(value = "商品详情页", notes = "返回商品数据，评论数据，图片数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", required = true, defaultValue = "1", value = "详情页所对应的商品id")
    })
    @GetMapping("/productDetails")
    public RequestResult<ProductDetails> productDetails(HttpServletRequest request, @RequestParam String productId) {
        log.info("调用service接口进行商品详情页查询，参数：{}", productId);

        String token1 = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token1);
        if (null != userService.queryUserByUserId(userId)) {
            log.info("------ 用户已经登录，加足迹 ------");
            // 浏览商品详情页即加入足迹
            trackApi.addTrack(userId, Integer.valueOf(productId));
        }
        log.info("------ 没有用户登录，正常浏览 ------");

        return ResultBuildUtil.success(searchService.queryProductDetails(productId));
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/17 12:27
     * @acl : true
     * @description :
     */
    @ApiOperation(value = "轮播图展示", notes = "返回轮播图数据，以及轮播图的跳转链接")
    @GetMapping("/rotationChart")
    @ApiImplicitParams({
    })
    public RequestResult<List<RotationChart>> rotationCharts() {
        log.info("调用service接口进行轮播图展示查询");
        return ResultBuildUtil.success(searchService.queryRotationCharts(1));
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/17 17:25
     * @acl : true
     * @description : 首页数据-小米有品众筹
     */
    @ApiOperation(value = "首页数据-小米有品众筹", notes = "只显示3条数据")
    @GetMapping("/crowdFunding")
    public RequestResult<List<Product>> crowdFunding() {
        log.info("调用service接口进行小米有品众筹查询");
        return ResultBuildUtil.success(searchService.queryCrowdFunding());
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/17 17:25
     * @acl : true
     * @description : 首页数据-有品秒杀
     */
    @ApiOperation(value = "首页数据-有品秒杀", notes = "只显示6条数据")
    @GetMapping("/secKill")
    public RequestResult<List<Product>> secKill() {
        log.info("调用service接口进行小米秒杀查询");
        return ResultBuildUtil.success(searchService.querySecKill());
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/17 17:25
     * @acl : true
     * @description : 首页数据-每日新品
     */
    @ApiOperation(value = "首页数据-每日新品", notes = "只显示6条数据")
    @GetMapping("/dailyNew")
    public RequestResult<List<Product>> dailyNew() {
        log.info("调用service接口进行每日新品查询");
        return ResultBuildUtil.success(searchService.queryDailyNew());
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/17 17:25
     * @acl : true
     * @description : 首页数据-专属推荐
     */
    @ApiOperation(value = "首页数据-专属推荐", notes = "最多显示12条数据，数据根据用户足迹和收藏专属定制")
    @ApiResponses({
    })
    @GetMapping("/queryVipRecommend")
    public RequestResult<List<Product>> queryVipRecommend(HttpServletRequest request) {
        // 校验数据
        Integer userId = getUserIdByToken(request);
        if (null == userId) {
            userId = 0;
        }
        if (-1 == userId) {
            userId = 0;
        }
        log.info("调用service接口进行专属推荐查询");
        return ResultBuildUtil.success(searchService.queryVipRecommend(userId));
    }


    /**
     * @author : Lcywings
     * @date : 2021/8/18 8:31
     * @acl : true
     * @description : 个人收藏
     */
    @ApiOperation(value = "加入个人收藏", notes = "点击即可加入/取消收藏，在5s内最多点3次")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", required = true, defaultValue = "1", value = "商品编码")
    })
    @ApiResponses({
            @ApiResponse(code = 4001, message = "点击过于频繁，请稍后再试！"),
            @ApiResponse(code = 4002, message = "用户未登录"),
            @ApiResponse(code = 4003, message = "不存在的商品编号")
    })
    @GetMapping("/collect")
    public RequestResult<String> collect(HttpServletRequest request, @RequestParam String productCode) {
        log.info("调用service接口将商品加入个人收藏");

        // 校验数据
        Integer userId = getUserIdByToken(request);
        Integer productId = getProductIdByproductCode(productCode);
        if (userId == -1) {
            return ResultBuildUtil.fail("4002", "用户未登录");
        }
        if (productId == -1) {
            return ResultBuildUtil.fail("4003", "不存在的商品编号");
        }

        // 查
        List<Boolean> booleans = searchService.addCollect(userId, productId);

        // 频率检查
        if (!booleans.get(0)) {
            return ResultBuildUtil.fail("4001", "点击过于频繁，请稍后再试");
        } else {
            if (booleans.get(1)) {
                return ResultBuildUtil.success("已加入个人收藏");
            } else {
                return ResultBuildUtil.success("已移除个人收藏");
            }
        }
    }

    /**
     * @author : Lcywings
     * @date : 2021/8/20 10:30
     * @acl : true
     * @description : 查询收藏列表
     */
    @ApiOperation(value = "查询收藏列表", notes = "支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", required = true, defaultValue = "5", value = "页面容量"), @ApiImplicitParam(name = "pageNo", required = true, defaultValue = "1", value = "当前页")
    })
    @ApiResponses({
            @ApiResponse(code = 4002, message = "用户未登录"), @ApiResponse(code = 4012, message = "用户没有收藏"), @ApiResponse(code = 4003, message = "不存在的商品编号")
    })
    @GetMapping("/collectList")
    public RequestResult<PageSupportUtil<UserCollectDetail>> collectList(HttpServletRequest request, @RequestParam Integer pageSize, @RequestParam Integer pageNo) {
        // 校验数据
        Integer userId = getUserIdByToken(request);
        if (userId == -1) {
            return ResultBuildUtil.fail("4002", "用户未登录");
        }

        log.info("调用service接口进行收藏列表查询，参数：用户Id:{}，商品Id:{}，页面容量:{},当前页:{}", userId, pageSize, pageNo);
        if (ObjectUtils.isEmpty(searchService.collectList(userId, pageSize, pageNo).getData())) {
            return ResultBuildUtil.fail("4012", "用户没有收藏");
        }

        return ResultBuildUtil.success(searchService.collectList(userId, pageSize, pageNo));
    }

    //根据token拿到userId
    private Integer getUserIdByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        return searchService.selectUserIdByToken(token);
    }

    //根据productCode拿到productId
    private Integer getProductIdByproductCode(String productCode) {
        return searchService.getProductIdByproductCode(productCode);
    }
}
